import React, { Component, PropTypes } from 'react';
import { Router, Route, IndexRoute, hashHistory  } from 'react-router';
import Api from '../../api'
import { Toast } from 'antd-mobile'
import { ajaxGetUser, getUser }  from 'Utils/auth'

import MainPage from './pages/index'; //首页
import Register from './pages/register'; //注册
import Invitation from './pages/invitation'; //邀请
import Guide from './pages/guide'; //引导
import Account from './pages/account'; //账户安全
import EditPhone from './pages/edit-phone'; //修改手机号
import Authen from './pages/authen'; //认证 - 上传图片
import EditEmail from './pages/edit-email'; //修改邮箱
import PickAddress from './pages/pick-address'; //修改邮箱
import AddAddress from './pages/add-address'; //添加地址
import Points from './pages/points'; //添加地址
import Withdraw from './pages/withdraw'; //提现
import OrderList from './pages/order-list'; //订单
import Mall from './pages/mall'; //商城
import ProductDetail from './pages/product-detail'; //广告详情
import GiftDetail from './pages/gift-detail'; //广告详情
import About from './pages/About'; //广告详情
import { pageNameMap } from './config'
import '../../assets/css/animate.less';

import { connect } from 'react-redux';
import { requestGetUser, setUserType, initUserInfo } from '../../store/actions';
import ReactCSSTransitionGroup from 'react/lib/ReactCSSTransitionGroup'

let FIRST_ENTER = true;

@connect(
  state=>state.app
)
class Roots extends Component {
    render() {
        return (
          <div>
            { this.props.children }
          </div>
        );
    }
    // componentDidMount(){
    //   // 从localStorage取出用户信息
    //   // this.props.dispatch(saveUserInfo());
    //   const userType = this.props.location.query.type || 1;
    //
    //   // this.props.dispatch(setUserType({ type: userType }));
    //   // this.props.dispatch(requestGetUser({ type: userType }));
    // }
}

function setTitle(titName){
  document.title = titName;
  if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
      var i = document.createElement('iframe');
      i.src = '/favicon.ico';
      i.style.display = 'none';
      i.onload = function() {
          setTimeout(function(){
              i.remove();
          }, 9)
      }
      document.body.appendChild(i);
  }
}

// 如果没有注册，则跳转到注册页
function initPage(prevState, nextState, replace, next){
  console.warn('change');
  const locationState = nextState.location;
  const type = locationState.query.type || 1;
  const pageName = locationState.pathname.replace('/', '');

  // 设置标题
  console.log(pageName);
  console.warn('======>',pageNameMap[pageName])

  const title = pageNameMap[pageName] || '首页';
  setTitle(title);

  let cacheUserData = getUser();

  if(pageName === 'register'){//进注册页
    if(!cacheUserData){
      return next();
    }else{
      replace({pathname:'/', query:{type:type}});
      return next();
    }
  }else if(cacheUserData){ //有缓存
    return next();
  }else{ //没有注册，不是注册页
    replace({pathname:'/register', query:{type:type}});
    return next();
  }

}

function checkRegist(nextState, replace, next){
  console.warn('Enter');
  const locationState = nextState.location;
  const type = locationState.query.type || 1;

  window.hashHistory = hashHistory;
  // 只要是第一次进入，必须获取一次用户信息
  if(!FIRST_ENTER){ return next(); }

  ajaxGetUser(type, function(res){
    if(res.errorCode === 200){
      console.log('已注册，保存');
      window._REDUX_STORE.dispatch(initUserInfo({ userInfo: res.data, userType: type }));
      replace({pathname:'/', query:{type:type}});
    }else{
      console.log('未注册，至注册页');
      window._REDUX_STORE.dispatch(initUserInfo({ userInfo: '', userType: type }));
      replace({pathname:'/register', query:{type:type}});
      setTitle('注册');
      // 跳审核中页面
    }
    FIRST_ENTER = false;
    next();
  }, function(){
    Toast.error('获取个人信息失败');
  })
}

const RouteConfig = (
    <Router history={ hashHistory }>
        <Route path="/" component={Roots} onEnter={ checkRegist }  onChange={ initPage }>
            <IndexRoute component={MainPage}/>
            <Route path="register" component={Register} />
            <Route path="invitation" component={Invitation} />
            <Route path="account" component={Account} />
            <Route path="editPhone" component={EditPhone} />
            <Route path="editEmail" component={EditEmail} />
            <Route path="authen" component={Authen} />
            <Route path="pickAddress" component={PickAddress} />
            <Route path="addAddress" component={AddAddress} />
            <Route path="points" component={Points} />
            <Route path="withdraw" component={Withdraw} />
            <Route path="orderList" component={OrderList} />
            <Route path="mall" component={Mall} />
            <Route path="productDetail" component={ProductDetail} />
            <Route path="giftDetail" component={GiftDetail} />
            <Route path="about" component={About} />
        </Route>
    </Router>
);

export default RouteConfig;
